<template>
    <view class="page tn-safe-area-inset-bottom">
        <!-- 顶部自定义导航 -->
        <view :style="{ height: vuex_custom_bar_height + 'px' }" class="tn-navbg">
            <tn-nav-bar alpha customBack fixed>
                <view slot="back" class="tn-custom-nav-bar__back" @click="goBack">
                    <text class="icon tn-icon-left"></text>
                    <text class="icon tn-icon-home-capsule-fill"></text>
                </view>
                <view class="tn-flex tn-flex-col-center tn-flex-row-center">
                    <text class="tn-text-bold tn-text-xl tn-color-black">
                        咨询室
                    </text>
                </view>
            </tn-nav-bar>
        </view>

        <!-- 页面实际内容 -->
        <view class="main">
            <!-- 订单信息卡片（替换顶部三个按钮） -->
            <view class="order-card order-floating" :style="{ top: (vuex_custom_bar_height + 16) + 'px' }">
                <view class="order-header">
                    <image class="logo" src="/static/images/discovery/transaction.png" mode="widthFix" />
                    <view class="title-price">
                        <view class="title tn-text-bold">{{ orderInfo.title }}</view>
                        <view class="price"><text class="unit">￥</text>{{ orderInfo.price }}<text class="unit">/小时</text></view>
                    </view>
                    <!-- <view class="time-badge">
                        <text class="icon tn-icon-voice-fill"></text>
                        <text>{{ orderInfo.duration }}</text>
                    </view> -->
                </view>
                <view class="order-body">
                    <view class="desc">{{ orderInfo.desc }}</view>
                    <view class="tags">
                        <view v-for="(tag, i) in orderInfo.tags" :key="i" class="tag">{{ tag }}</view>
                    </view>
                </view>
                <view class="order-footer">
                    <navigator :url="`/discoverypages/order?mode=update&id=${projectId}`" class="order-action secondary">
                        <text>修改订单</text>
                    </navigator>
                    <view class="order-action primary" @click="showConfirmModal">
                        <text>确认交易</text>
                    </view>
                </view>
            </view>
            <!-- 聊天区 -->
            <view class="chatbox">
<!--                <message v-for="(item) in messages" :key="item.id" :messageId="item.id" :content="item.content" />-->
              <view class="page-content">
                <scroll-view
                  class="scroll-view"
                  scroll-y
                  scroll-with-animation
                  :scroll-top="scrollTop"
                  @scrolltoupper="onScrollToUpper"
                  :refresher-enabled="hasMoreHistory"
                  :refresher-triggered="isLoadingHistory"
                  @refresherrefresh="onRefreshHistory"
                >
                  <view style="padding: 30rpx 0 240rpx;">
                    <!-- 加载提示 -->
                    <view v-if="isLoadingHistory" class="loading-tip">
                      <text>正在加载历史消息...</text>
                    </view>

                    <!-- 没有更多历史消息提示 -->
                    <view v-else-if="!hasMoreHistory && list.length > 0" class="no-more-tip">
                      <text>没有更多历史消息了</text>
                    </view>

                    <view class="message" :class="[item.userType]" v-for="(item,index) in list.slice().reverse()" :key="item.messageId || index">
                      <!-- 头像 -->
                      <view class="avatar">
                        <text v-if="item.userType === 'self'">我</text>
                        <text v-else>{{ item.senderId && item.senderId !== senderId.value ? item.senderId.slice(-2) : '客' }}</text>
                      </view>

                      <!-- 消息内容 -->
                      <view class="content" v-if="item.messageType === 'image'">
                        <image :src="item.content" mode="widthFix"></image>
                      </view>
                      <view class="content" v-else>
                        {{ item.content }}
                      </view>
                    </view>
                  </view>
                </scroll-view>
              </view>
            </view>
            <!-- 底部输入框 -->
            <view class="footer">
                <view class="input">
                    <tn-input v-model="draft" placeholder="输入消息..." placeholderStyle="color: #9CA3AF" />
                </view>
                <tn-button @click="sendMeg" class="send" width="128rpx" height="80rpx" backgroundColor="#007AFF"
                    fontColor="white">发送</tn-button>
            </view>
        </view>

        <!-- 确认交易弹窗 -->
        <tn-modal 
            v-model="confirmModalVisible" 
            title="温馨提醒" 
            content="是否确认与此接单者交易？交易后会自动创建企业微信群。" 
            :button="confirmModalButtons"
            @click="handleConfirmModalClick"
        ></tn-modal>
    </view>
</template>

<script setup>
import useTemplatePageMixin from '@/libs/mixin/use_template_page_mixin';
import { onReady, onLoad, onUnload } from '@dcloudio/uni-app';
import { ref } from '@vue/composition-api';
import {UniWebSocketClient} from '@/util/socket';
import { loadInitialMessages, loadHistoryMessages, confirmTransaction } from '@/api/message';
import {connectGoEasy, initGoEasy, publishMessage, subscribeChannel} from "@/util/socketV2";

const { goBack } = useTemplatePageMixin()
const list = ref([]);

// 订单信息展示（用于顶部信息卡片）
const orderInfo = ref({
    title: '订单标题',
    price: 30,
    duration: '17″',
    desc: '您好，我是某某，从业多年，支持需求沟通…',
    tags: ['程序开发', '网页开发']
})

// 页面参数
const conversationId = ref('')
const projectId = ref('')
const merchantopenId = ref('')
const receiverId = ref('')  // 接收人ID（原senderId参数）
const lastId = ref('')
const pageSize = ref(5)

// 当前用户信息
const currentUserInfo = ref(null)
const senderId = ref('')  // 当前用户ID

// 滚动相关
const scrollTop = ref(0)
const isLoadingHistory = ref(false)
const hasMoreHistory = ref(true) // 是否还有更多历史消息

// 确认交易弹窗相关
const confirmModalVisible = ref(false)
const confirmModalButtons = [
    {
        text: '取消',
        backgroundColor: '#E5E7EB',
        fontColor: '#374151',
    },
    {
        text: '确认',
        backgroundColor: '#007AFF',
        fontColor: '#FFFFFF',
    }
]

// 显示确认弹窗
const showConfirmModal = () => {
    confirmModalVisible.value = true
}

// 处理弹窗按钮点击
const handleConfirmModalClick = async (e) => {
    const { index } = e
    if (index === 1) {
        // 点击了确认按钮
        console.log('用户确认交易')

        try {
            // 调用确认交易接口
            const res = await confirmTransaction(merchantopenId.value, projectId.value)

            if (res.code === 200) {
                // 交易确认成功
                uni.showToast({
                    title: '交易确认成功',
                    icon: 'success'
                })
                console.log('交易确认成功:', res.data)
                
                // 检查是否有有效的项目ID
                if (projectId.value) {
                    console.log('准备跳转到订单详情页面，项目ID:', projectId.value)
                    // 跳转到订单详情页面
                    setTimeout(() => {
                        const targetUrl = `/homepages/detail?id=${projectId.value}`
                        console.log('跳转URL:', targetUrl)
                        uni.navigateTo({
                            url: targetUrl,
                            success: () => {
                                console.log('跳转成功')
                            },
                            fail: (err) => {
                                console.error('跳转失败:', err)
                                uni.showToast({
                                    title: '跳转失败，请手动返回',
                                    icon: 'none'
                                })
                            }
                        })
                    }, 1500) // 延迟1.5秒跳转，让用户看到成功提示
                } else {
                    console.warn('项目ID为空，无法跳转到详情页面')
                    uni.showToast({
                        title: '交易确认成功，但缺少项目信息',
                        icon: 'none'
                    })
                }
            } else {
                // 交易确认失败
                uni.showToast({
                    title: res.msg || '交易确认失败',
                    icon: 'error'
                })
                console.error('交易确认失败:', res.msg)
            }
        } catch (error) {
            // 网络错误或其他异常
            uni.showToast({
                title: '网络错误，请重试',
                icon: 'error'
            })
            console.error('确认交易接口调用失败:', error)
        }
    }
    confirmModalVisible.value = false
}

/**
 * 聊天记录
 */

/**
 * 输入草稿
 */

const draft = ref('')
let wsClient = null;

// 页面加载时获取参数
 onLoad( async (options) => {
    console.log('页面参数:', options)
    if (options.id) {
        conversationId.value = options.id
    }
    if (options.projectId) {
        projectId.value = options.projectId
    }
    if (options.merchantopenId) {
        merchantopenId.value = options.merchantopenId
    }
    if (options.receiverId) {
        receiverId.value = options.receiverId  // 接收人ID（商户ID）
    }

    // 获取当前用户信息
    const userInfo = uni.getStorageSync("userInfo")
    if (userInfo && userInfo.openId) {
        currentUserInfo.value = userInfo
        senderId.value = userInfo.openId  // 设置当前用户ID为openId
        console.log('当前用户信息:', userInfo)
        console.log('当前用户ID (senderId):', senderId.value)
    } else {
        console.warn('未找到用户信息或openId')
    }

    console.log('接收到的参数:', {
        conversationId: conversationId.value,
        projectId: projectId.value,
        merchantopenId: merchantopenId.value,
        receiverId: receiverId.value,
        senderId: senderId.value
    })

    await initGoEasy("BC-0910ecd4492c4356a43654a8b4af49c3");
    connectGoEasy("user-002", { nickname: "Neo" });
    subscribeChannel(projectId.value + "_" + conversationId.value + userInfo.openId, (msg) => {
      console.log(msg, "---msg")
      const content = msg.content
      const msgJson = JSON.parse(content);
      // 生成临时messageId（实际项目中应该从服务器返回）
      const tempMessageId = 'ws_' + Date.now()
      list.value.push({
        messageId: tempMessageId,
        content: msgJson.msg,
        userType: 'friend',
        avatar: "",
        createTime: new Date().toLocaleString(),
        senderId: msgJson.senderId || 'friend'
      })
      // messages.value.push({ content: msg.content });
    });

    // 加载消息列表
    if (conversationId.value) {
        loadMessages()
    }
})

onReady(async () => {
    console.log('chat page ready')
  // wsClient = new UniWebSocketClient("wss://325b82634t.vicp.fun/ws");
  // wsClient.onMessage((msg) => {
  //   console.log("📨 页面收到消息:", msg);
  //   const msgJson = JSON.parse(msg);
  //
  //   // 生成临时messageId（实际项目中应该从服务器返回）
  //   const tempMessageId = 'ws_' + Date.now()
  //
  //   list.value.push({
  //     messageId: tempMessageId,
  //     content: msgJson.msg,
  //     userType: 'friend',
  //     avatar: "",
  //     createTime: new Date().toLocaleString(),
  //     senderId: msgJson.senderId || 'friend'
  //   })
  //   // 可以更新数据、展示 UI 等
  // });

})

onUnload(() => {
    if (wsClient) {
        wsClient.close();
        console.log('WebSocket connection closed.');
    }
})

// 加载消息列表
const loadMessages = async () => {
    const result = await loadInitialMessages(projectId.value + "_" + conversationId.value, pageSize.value)

    if (result.success) {
        list.value = result.messages
        lastId.value = result.lastId
        hasMoreHistory.value = result.hasMore
    } else {
        console.error('获取消息失败:', result.error)
        uni.showToast({
            title: result.error,
            icon: 'error'
        })
    }
}

// 加载历史消息
const loadHistoryMessagesHandler = async () => {
    if (isLoadingHistory.value || !hasMoreHistory.value) {
        console.log('跳过加载历史消息:', { isLoading: isLoadingHistory.value, hasMore: hasMoreHistory.value })
        return
    }

    try {
        isLoadingHistory.value = true
        const result = await loadHistoryMessages(projectId.value + "-" + conversationId.value, list.value, pageSize.value)

        if (result.success) {
            if (!result.isEmpty && result.messages.length > 0) {
                // 将历史消息追加到列表末尾
                list.value = [...list.value, ...result.messages]
                console.log('更新后的列表长度:', list.value.length)
            }

            // 更新是否还有更多历史消息的状态
            hasMoreHistory.value = result.hasMore

            if (!result.hasMore) {
                console.log('没有更多历史消息了')
            }
        } else {
            console.error('获取历史消息失败:', result.error)
            uni.showToast({
                title: result.error,
                icon: 'error'
            })
        }
    } finally {
        isLoadingHistory.value = false
    }
}

// 滚动到顶部时触发
const onScrollToUpper = () => {
    if (!hasMoreHistory.value) {
        console.log('没有更多历史消息，跳过加载')
        return
    }
    console.log('滚动到顶部，开始加载历史消息')
    loadHistoryMessagesHandler()
}

// 下拉刷新历史消息
const onRefreshHistory = () => {
    if (!hasMoreHistory.value) {
        console.log('没有更多历史消息，跳过刷新')
        // 结束刷新状态
        setTimeout(() => {
            isLoadingHistory.value = false
        }, 500)
        return
    }
    console.log('下拉刷新历史消息')
    loadHistoryMessagesHandler()
}

const sendMeg = () => {
  if (wsClient) {

  }
  publishMessage(projectId.value + "_" + conversationId.value + merchantopenId.value, JSON.stringify({
    type: "single",
    msg: draft.value,
    to: receiverId.value || "456",  // 使用接收人ID
    conversationId: projectId.value + "_" + conversationId.value,
    senderId: senderId.value  // 使用当前用户ID
  }));
  // 生成临时messageId（实际项目中应该从服务器返回）
  const tempMessageId = 'temp_' + Date.now()

  list.value.push({
    messageId: tempMessageId,
    content: draft.value,
    userType: 'self',
    avatar: "",
    createTime: new Date().toLocaleString(),
    senderId: senderId.value  // 使用当前用户ID而不是'self'
  })
  draft.value = '' // 清空输入框
}
</script>

<style lang="scss" scoped>
.tn-custom-nav-bar__back {
    width: 100%;
    height: 100%;
    position: relative;
    display: flex;
    justify-content: space-evenly;
    align-items: center;
    box-sizing: border-box;
    background-color: rgba(0, 0, 0, 0.15);
    border-radius: 1000rpx;
    border: 1rpx solid rgba(255, 255, 255, 0.5);
    color: #ffffff;
    font-size: 18px;

    .icon {
        display: block;
        flex: 1;
        margin: auto;
        text-align: center;
    }

    &:before {
        content: " ";
        width: 1rpx;
        height: 110%;
        position: absolute;
        top: 22.5%;
        left: 0;
        right: 0;
        margin: auto;
        transform: scale(0.5);
        transform-origin: 0 0;
        pointer-events: none;
        box-sizing: border-box;
        opacity: 0.7;
        background-color: #ffffff;
    }
}

.page-content {
    display: flex;
    flex-direction: column;
    height: 70vh;
    background: linear-gradient(180deg, #F8FAFC 0%, #F1F5F9 100%);
}

.loading-tip {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 30rpx 20rpx;
    color: #64748B;
    font-size: 26rpx;
    background: rgba(255, 255, 255, 0.8);
    margin: 20rpx;
    border-radius: 16rpx;
    backdrop-filter: blur(10rpx);
}

.no-more-tip {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 20rpx;
    color: #9CA3AF;
    font-size: 24rpx;
}

.main {
    display: flex;
    flex: 1;
    flex-direction: column;
    gap: 8rpx;
    margin: 20rpx 32rpx 30rpx 32rpx;
}

.header {
    display: flex;
    justify-content: space-between;
    gap: 16rpx;

    .action {
        image {
            margin-right: 12rpx;
        }

        text {
            color: white;
            white-space: nowrap;
        }
    }
}

/* 订单信息卡片样式 */
.order-card {
    background: #ffffff;
    border-radius: 20rpx;
    box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.06);
    padding: 24rpx;
}

.order-floating {
    position: fixed;
    left: 32rpx;
    right: 32rpx;
    z-index: 1000;
}

.order-header {
    display: flex;
    align-items: center;
    gap: 20rpx;
}

.order-header .logo {
    width: 80rpx;
    height: 80rpx;
}

.order-header .title-price {
    flex: 1;
}

.order-header .title {
    font-size: 30rpx;
    color: #111827;
    margin-bottom: 6rpx;
}

.order-header .price {
    color: #EF4444;
    font-size: 34rpx;
}

.order-header .price .unit {
    font-size: 26rpx;
}

.time-badge {
    background: #E0F2FE;
    color: #0369A1;
    border-radius: 40rpx;
    padding: 8rpx 16rpx;
    font-size: 24rpx;
    display: flex;
    align-items: center;
    gap: 8rpx;
}

.order-body {
    margin-top: 16rpx;
    color: #6B7280;
    font-size: 26rpx;
}

.order-body .tags {
    margin-top: 12rpx;
    display: flex;
    flex-wrap: wrap;
    gap: 12rpx;
}

.order-body .tag {
    background: #F3F4F6;
    color: #6B7280;
    font-size: 22rpx;
    border-radius: 28rpx;
    padding: 6rpx 14rpx;
}

.order-footer {
    margin-top: 20rpx;
    display: flex;
    gap: 16rpx;
}

.order-action {
    flex: 1;
    text-align: center;
    border-radius: 12rpx;
    padding: 20rpx 0;
    font-size: 28rpx;
}

.order-action.primary {
    background: #007AFF;
    color: #ffffff;
}

.order-action.secondary {
    background: #E5E7EB;
    color: #374151;
}

.chatbox {
    display: flex;
    flex: 1;
    flex-direction: column;
    border-radius: 24rpx;
    background-color: #F8FAFC;
    overflow: hidden;
    /* 预留悬浮订单卡片的高度，避免消息被覆盖 */
    margin-top: 260rpx;
}

.footer {
    display: flex;
    align-items: center;
    gap: 16rpx;
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 1000;
    background: #ffffff;
    padding: 12rpx 32rpx calc(env(safe-area-inset-bottom, 0px) + 12rpx) 32rpx;
    border-radius: 0;
    box-shadow: none;
    border-top: 1rpx solid #EEF2F7;

    .input {
        flex: 1;
        padding: 12rpx 32rpx;
        border-radius: 24rpx;
        background: #F3F4F6;
        font-size: 28rpx;
    }
}
.scroll-view {
  /* #ifdef H5 */
  height: calc(100vh - 44px);
  /* #endif */
  /* #ifndef H5 */
  height: 100%;
  /* #endif */
  box-sizing: border-box;
  background: transparent;
  /* 预留底部输入栏空间，避免遮挡 */
  padding-bottom: 160rpx;
}
.message {
  display: flex;
  align-items: flex-start;
  margin-bottom: 30rpx;
  padding: 0 20rpx;

  .avatar {
    width: 80rpx;
    height: 80rpx;
    border-radius: 40rpx;
    margin-right: 20rpx;
    background: #E5E7EB;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24rpx;
    color: #6B7280;
    flex-shrink: 0;
  }

  .content {
    min-height: 60rpx;
    max-width: 60vw;
    box-sizing: border-box;
    font-size: 30rpx;
    line-height: 1.4;
    padding: 24rpx 28rpx;
    border-radius: 20rpx;
    background: #fff;
    position: relative;
    word-wrap: break-word;
    word-break: break-all;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);

    image {
      width: 200rpx;
    }
  }

  &.self {
    justify-content: flex-end;
    flex-direction: row-reverse;

    .avatar {
      margin: 0 0 0 20rpx;
      background: #007AFF;
      color: white;
    }

    .content {
      background: #007AFF;
      color: white;
      border-radius: 20rpx 20rpx 8rpx 20rpx;

      &::after {
        position: absolute;
        content: '';
        width: 0;
        height: 0;
        border: 12rpx solid transparent;
        border-left: 12rpx solid #007AFF;
        right: -20rpx;
        top: 20rpx;
      }
    }
  }

  &.friend {
    .avatar {
      background: #10B981;
      color: white;
    }

    .content {
      background: #F3F4F6;
      color: #1F2937;
      border-radius: 20rpx 20rpx 20rpx 8rpx;

      &::after {
        position: absolute;
        content: '';
        width: 0;
        height: 0;
        border: 12rpx solid transparent;
        border-right: 12rpx solid #F3F4F6;
        left: -20rpx;
        top: 20rpx;
      }
    }
  }
}
</style>